//
//  21_合并两个有序链表.swift
//  Swift-LeetCode
//
//  Created by 卢悦明 on 2024/3/2.
/**
 https://leetcode.cn/problems/merge-two-sorted-lists/description/
 */

import UIKit

class BinarySolution: NSObject {
    func mergeTwoLists(_ list1: ListNode<Int>?, _ list2: ListNode<Int>?) -> ListNode<Int>? {
        let newHeader = ListNode(-1);
        var list1 = list1
        var list2 = list2
        var currentNode = newHeader
        while let listNode1 = list1, let listNode2 = list2  {
            if listNode1.val < listNode2.val {
                currentNode.next = listNode1
                currentNode = listNode1
                list1 = listNode1.next
            } else {
                currentNode.next = listNode2
                currentNode = listNode2
                list2 = listNode2.next
            }
        }
        if list1 == nil {
            currentNode.next = list2
        } else {
            currentNode.next = list1
        }
        return newHeader.next
    }
}
